package com.kk.xhr.model.service.impl;

import com.kk.xhr.common.pojo.BinaryEnum;
import com.kk.xhr.model.dao.PositionDynamicSqlSupport;
import com.kk.xhr.model.dao.PositionMapper;
import com.kk.xhr.model.dto.PositionDTO;
import com.kk.xhr.model.entity.Position;
import com.kk.xhr.model.service.IPositionService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.kk.xhr.common.RedisConstant.POSITION_CACHE;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;

/**
 * 职位服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/4
 * @since 1.0.0
 */
@Repository
@RequiredArgsConstructor
@CacheConfig(cacheNames = POSITION_CACHE)
public class PositionServiceImpl implements IPositionService {
    private final PositionMapper positionMapper;

    @Override
    public List<PositionDTO> query() {
        return positionMapper.select(dsl -> dsl
            .where(PositionDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue())))
            .stream()
            .map(entity -> PositionDTO.builder()
                .id(entity.getId())
                .name(entity.getName())
                .build())
            .collect(Collectors.toList());
    }

    @Override
    @Cacheable(key = "#id")
    public Optional<PositionDTO> queryById(Long id) {
        return positionMapper.selectOne(dsl -> dsl
            .where(PositionDynamicSqlSupport.id, isEqualTo(id))
            .and(PositionDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue())))
            .map(entity -> PositionDTO.builder()
                .id(entity.getId())
                .name(entity.getName())
                .status(BinaryEnum.from(entity.getStatus()))
                .build());
    }

    @Override
    public boolean add(PositionDTO dto) {
        return 1 == positionMapper.insertSelective(new Position().withName(dto.getName()));
    }

    @Override
    @CacheEvict(key = "#p0.id")
    public boolean modify(PositionDTO dto) {
        if (null == dto.getId()) {
            return false;
        }
        return 1 == positionMapper.updateByPrimaryKeySelective(
            new Position().withId(dto.getId()).withName(dto.getName()));
    }

    @Override
    @CacheEvict(key = "#id")
    public boolean modifyStatus(Long id, BinaryEnum status) {
        return 1 == positionMapper.updateByPrimaryKeySelective(new Position().withId(id).withStatus(status.getValue()));
    }

    @Override
    public boolean existName(String name) {
        return positionMapper.selectOne(dsl -> dsl
            .where(PositionDynamicSqlSupport.name, isEqualTo(name))
            .and(PositionDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue())))
            .isPresent();
    }
}
